<script setup lang="ts">
import {
    defineComponent,
    toRefs,
    reactive,
    getCurrentInstance
}
    from 'vue'
import type {FormInstance, UploadFile, UploadRawFile} from "element-plus";
import {UploadFilled} from '@element-plus/icons-vue'
import type {UploadInstance, UploadFiles} from 'element-plus'
import {AiService} from "/@/api/openapi";
import {ElMessage} from "element-plus";
import {base64ConvertFile, convertFileToBase64, getNewFile, isFileChanged} from "/@/utils/convert"
import type {UploadProps, UploadUserFile} from 'element-plus'


const formData = reactive({
    file: "",
    model: "best.pt",
    confThreshold: 0.25,
    iouThreshold: 0.4,
});
import {ElLoading} from 'element-plus'

const fullscreenLoading = ref(false)
const openFullScreen1 = () => {
    fullscreenLoading.value = true
}

const rules = reactive({})

const base64Url = ref<string>("")
const fileName = ref<string>("")


const modelOptions = reactive([{
    label: "best.pt",
    value: "best.pt",
    disabled: false
}, {
    label: "yolov5s.pt",
    value: "yolov5s.pt",
    disabled: false
}])

const vForm = ref<FormInstance>()
const instance = getCurrentInstance()
const submitForm = () => {
    if (vForm.value !== undefined) {
        vForm.value.validate(valid => {
            if (!valid) return
            //TODO: 提交表单
        })
    }
}
const resetForm = () => {
    if (vForm.value !== undefined) {
        vForm.value.resetFields()
    }
}


const this_file = ref<File>();


/**
 * 检测文件内容是否被更改
 * @param { File } file
 * @returns {Promise<boolean>} 内容是否被更改
 */

const submit = async () => {
    console.log(formData)
    console.log(this_file.value)
    if (this_file.value === null || this_file.value === undefined) {
        ElMessage.error("图片还未上传")
        return
    }
    if (formData.model === null || formData.model === undefined) {
        ElMessage.error("模型未选择")
        return
    }
    if (formData.confThreshold === null || formData.confThreshold === undefined) {
        ElMessage.error("阈值错误")
        return
    }
    if (formData.iouThreshold === null || formData.iouThreshold === undefined) {
        ElMessage.error("MIOU阈值错误")
        return
    }
    last.value = this_file.value.lastModified
    const loading = ElLoading.service({
        lock: true,
        text: '正在请求后台',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    try {
        const new_file = base64ConvertFile(base64Url.value, fileName.value)
        console.log(new_file)
        AiService.getAiResult(formData.model, formData.confThreshold, formData.iouThreshold, {
            file: new_file
        }).then((res) => {
            console.log(res)
            if (res.data !== undefined) {
                updateResult(res.data)
                if (this_file.value !== undefined) {
                    this_file.value = new File([this_file.value.slice(0, this_file.value.size, this_file.value.type)], this_file.value.name)
                }
            }
            ElMessage.success(res)
        }, (error) => {
            console.log("reject错误")
            ElMessage.error("待修bug，暂不支持edge，请重新上传")
        }).catch((error) => {
            console.log("错误")
            ElMessage.error(error)
        }).finally(() => {
            loading.close()
        })
    } catch (error) {
        loading.close()
        console.log(error)
    }
}

// 声明事件
const emitsEventList = defineEmits(['updateResult', 'updateBase64'])

const updateResult = async (base64: string) => {
    emitsEventList("updateResult", base64)
}

const updateBase64 = async (base64: File) => {
    base64Url.value = await convertFileToBase64(base64)
    fileName.value = base64.name
    emitsEventList("updateBase64", base64)
}
const reset = () => {
    console.log("重置")
    formData.file = "";
    formData.model = "best.pt"
    formData.confThreshold = 0.25
    formData.iouThreshold = 0.4
}
const uploadRef = ref<UploadInstance>()

const on_preview = (uploadFile: UploadFile) => {
    console.log(uploadFile)
}

const before_remove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log("移除文件")
    console.log(uploadFile)
    console.log(uploadFiles)
}

const file_list = ref<UploadUserFile[]>()

const last = ref<number>(-1)



const on_change = (files: File[], uploadFiles: UploadUserFile[]) => {
    console.log("文件发生改变")
    console.log(uploadFiles);
    console.log(uploadFiles)

    file_list.value = []
    file_list.value.push({
        name: uploadFiles[0].name,
        uid: uploadFiles[0].uid
    })
    console.log(file_list.value)
    this_file.value = uploadFiles[0].raw;
    if (uploadFiles[0].raw !== undefined) {
        updateBase64(uploadFiles[0].raw);
    }
}

const on_exceed = (files: File[], uploadFiles: UploadUserFile[]) => {
    console.log("当超出限制时，执行的钩子函数")
    // ElMessage.error("图片只能上传1张，")
    console.log(files)
    console.log(uploadFiles)
    file_list.value = []
    file_list.value.push({
        name: files[0].name,
    })
    // 修改页面
    this_file.value = files[0];
    updateBase64(files[0]);
}
const limitNum = ref<number>(0)
const imgType = ['jpg', 'jpeg', 'png'];

const getLimit = (): boolean => {
    return limitNum.value > 0
}
</script>

<template>
    <el-form class="form" :model="formData" ref="vForm" :rules="rules" label-position="top" label-width="80px"
             size="default"
             @submit.prevent>
        <div class="card-container">
            <el-card style="{width: 100% !important}" shadow="always">
                <template #header>
                    <div class="clear-fix">
                        <span>大坝识别</span>
                    </div>
                </template>

                <el-form-item label="图片选择" class="choose-pic">
                    <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            drag

                            v-model:file-list="file_list"
                            :on-change="on_change"
                            :on-preview="on_preview"
                            :on-exceed="on_exceed"
                            :limit="1"
                            :before-remove="before_remove"
                            :auto-upload="false"
                            action="#"
                    >
                        <el-icon class="el-icon--upload">
                            <upload-filled/>
                        </el-icon>
                        <div class="el-upload__text">
                            拖拽文件 或者 <em>点击上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                必须得是jpg格式的文件
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="模型选择" prop="model">
                    <el-select v-model="formData.model" class="full-width-input" clearable>
                        <el-option v-for="(item, index) in modelOptions" :key="index" :label="item.label"
                                   :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="置信度阈值" prop="threshold">
                    <el-slider v-model="formData.confThreshold" :min=0 :max=1 :step="0.05" show-input></el-slider>
                </el-form-item>
                <el-form-item label="MIOU阈值" prop="confidence">
                    <el-slider v-model="formData.iouThreshold" :min=0 :max=1 :step="0.05" show-input></el-slider>
                </el-form-item>
                <el-row>
                    <el-col :span="4" class="grid-cell">
                        <div class="static-content-item">
                            <el-button @click="submit" type="primary">确认</el-button>
                        </div>
                    </el-col>
                    <el-col :span="4" class="grid-cell">
                        <div class="static-content-item">
                            <el-button>重置</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-card>
        </div>
    </el-form>
</template>


<style lang="scss">
.form {
  height: 100%;
}

.choose-pic {
  //max-height: 200px;
}

.upload-demo {
  width: 100%;
}

.el-upload-dragger {
  padding-top: 10px;
  padding-bottom: 10px;
}

.el-input-number.full-width-input,
.el-cascader.full-width-input {
  width: 100% !important;
}


.el-form-item--medium {
  .el-radio {
    line-height: 36px !important;
  }

  .el-rate {
    margin-top: 8px;
  }
}

.el-form-item--small {
  .el-radio {
    line-height: 32px !important;
  }

  .el-rate {
    margin-top: 6px;
  }
}

.el-form-item--mini {
  .el-radio {
    line-height: 28px !important;
  }

  .el-rate {
    margin-top: 4px;
  }
}

.clear-fix:before,
.clear-fix:after {
  display: table;
  content: "";
}

.clear-fix:after {
  clear: both;
}

.float-right {
  float: right;
}

</style>

<style lang="scss" scoped>
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    td.table-cell {
      display: table-cell;
      height: 36px;
      border: 1px solid #e1e2e3;
    }
  }
}

div.tab-container {
}

.label-left-align :deep(.el-form-item__label) {
  text-align: left;
}

.label-center-align :deep(.el-form-item__label) {
  text-align: center;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}

.custom-label {
}

.static-content-item {
  min-height: 20px;
  display: flex;
  align-items: center;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }
}

</style>